<?php
declare(strict_types=1);

namespace Modules\Teacher\Http\Requests;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Modules\Develop\Support\Generate\Create\Request;
use Modules\Grade\Models\Grade;
use Modules\Subject\Models\Subject;
use Modules\SubjectConfig\Models\SubjectConfig;
use Modules\Teacher\Models\Teacher;
use Modules\User\Models\User;


class TeacherController extends Controller
{
    public function __construct(
        protected readonly Teacher $model
    ){}

    /**
     * @return mixed
     */
    public function index(): mixed
    {
        $result = [];
        $teachers = Teacher::query()->where('status',1)->select(['id',"name","phone","subject_ids"])->get();
        $subjects = Subject::query()->get();
        $gradeArr = $this->translateKeyArr(Grade::query()->where('status',1)->get());

        foreach ($teachers as $key => $teacher)
        {
            $result[$key]['id'] = $teacher['id'];
            $result[$key]['name'] = $teacher['name'];
            $result[$key]['phone']= $teacher['phone'];

            $gradeSubs  = [];
            $subjectIds = explode(",",$teacher['subject_ids']);
            foreach ($subjects as $subject)
            {
                if (in_array($subject['id'],$subjectIds))
                {
                    $gradeSubs[] = [
                        "grade_id" => $subject['grade_id'],
                        "grade_name" => $gradeArr[$subject['grade_id']]['name'] ?? "",
                        "subject_id" => $subject['id'],
                        "subject_name" => $subject['name'],
                    ];
                }
            }

            $result[$key]['grade_subject'] = $gradeSubs;
        }

        return array_values($result);
    }

    public function add(TeacherRequest $request)
    {
        $data  = [];
        $param = $request->all();

        if (empty($param['name']) || empty($param['phone']) || empty($param['subject_ids']))
        {
            throw new FailedException("教师信息不完整，请重新填写~");
        }

        $data['name'] = $param['name'];
        $data['phone'] = $param['phone'];
        $data['subject_ids'] = $param['subject_ids'];

        $teacher = Teacher::query()->where(['phone'=>$data['phone'], 'status' => 1])->get();
        if (count($teacher))
        {
            throw new FailedException("教师手机号已存在，请更换");
        }

        if ($this->model->createBy($data))
        {
            return $this->addUser($data);
        }

        throw new FailedException("教师添加失败");
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(TeacherRequest $request)
    {
        return $this->model->storeBy($request->all());
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(TeacherRequest $request)
    {
        $params  = $request->all();
        $teacher = Teacher::query()->where('id',$params['id'])->first();

        if (empty($teacher))
        {
            throw new FailedException("教师信息不存在");
        }

        $sameData = Teacher::query()->where(['phone'=>$params['phone'],'status'=>1])->first();
        if ($sameData)
        {
            if($sameData['id'] != $params['id']) throw new FailedException("手机号已存在");
        }

        $update = [];

        if(isset($params['name'])) $update['name'] = $params['name'];
        if(isset($params['phone'])) $update['phone'] = $params['phone'];
        if(isset($params['subject_ids'])) $update['subject_ids'] = $params['subject_ids'];

        if ($this->updateUser($params, $teacher))
        {
            return $this->model->updateBy($params['id'],$update);
        }

        throw new FailedException("教师信息编辑失败");
    }

    /**
     * @param TeacherRequest $request
     * @return bool|null
     */
    public function delete(TeacherRequest $request)
    {
        $params = $request->all();

        if (!empty($params['id']))
        {
            $teacher= Teacher::query()->where('id',$params['id'])->first();
            $user = User::query()->where('email',$teacher['phone'])->first();

            $data['status'] = 2;
            if ($this->model->updateBy($params['id'],$data))
            {
                return (new User())->updateBy($user['id'], $data);
            }
        }

        throw new FailedException("删除教师信息失败");
    }

    public function reset(TeacherRequest $request)
    {
        $id = $request->get("id");
        $pw = $request->get("password");

        if(empty($id) || empty($pw)) throw new FailedException("重置密码失败，请重试");

        $teacher = Teacher::query()->where('id',$id)->first();
        if(empty($teacher)) throw new FailedException("教师信息不存在");

        $user = User::query()->where('email',$teacher['phone'])->first();
        $save = ["password" => $pw];

        return (new User())->updateBy($user['id'], $save);
    }

    protected function addUser($data)
    {
        $user['email'] = $data['phone'];
        $user['username'] = $data['name'];
        $user['password'] = "TL".substr($data['phone'],4,6);
        $user['roles'] = [1];
        $user['jobs'] = [];

        $userModel = new User();
        return $userModel->storeBy($user);
    }

    protected function updateUser($param, $teacher)
    {
        $save = [];
        $user = User::query()->where('email',$teacher['phone'])->first();
        if (empty($user))
        {
            throw new FailedException("用户不存在");
        }

        if (isset($param['phone']))
        {
            $save['email'] = $param['phone'];
        }

        if (isset($param['name']))
        {
            $save['username'] = $param['name'];
        }

        $userModel = new User();
        return $userModel->updateBy($user['id'], $save);
    }

    protected function translateKeyArr($data = [], $field = "id")
    {
        $result = [];
        foreach ($data as $datum)
        {
            $result[$datum[$field]] = $datum;
        }
        return $result;
    }
}
